package tech.mhuang.ext.netty.sample.server;

import tech.mhuang.core.close.BaseCloseable;
import tech.mhuang.ext.netty.server.AbstractNettyServer;
import tech.mhuang.ext.netty.sample.handler.TestServerChannelInitializerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author mHuang
 * @version V1.0.0
 * @Description netty 服务器
 * @date 2015年7月16日 下午3:05:17
 */
public class TestNettyServer extends AbstractNettyServer implements BaseCloseable {

    public Logger logger = LoggerFactory.getLogger(getClass());

    private static final long serialVersionUID = 1L;

    @Override
    public void bind() {
        bind(port);
    }

    @Override
    public void bind(int port) {
        logger.info("====begin nettyServer bind====");
        // config nio thread group
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // config client aotu property
            logger.info("====begin nettyServer configuation property====");
            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 1024);
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new TestServerChannelInitializerHandler());
            logger.info("====end nettyServer configuation property====");
            // bind port wait..
            logger.info("====begin nettyServer bind port====");
            ChannelFuture f = b.bind(port).sync();
            logger.info("====end nettyServer bind port====");
            // 等到服务端监听端口关闭
            f.channel().closeFuture().sync();
            logger.info("====end nettyServer bind====");
            logger.info("====nettyServer start ok!====");
        } catch (InterruptedException e) {
            logger.error("==== connection nettyServer interruptedException", e);
            e.printStackTrace();
        } finally {
            logger.info("====begin release nettyServer resource====");
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            logger.info("====end release nettyServer resource====");
        }
    }

    @Override
    public void close() {
        logger.info("====nettyServer closed=====");
    }
}
